package com.mt.mtbletools;

import com.mt.help.GlobalVariable;
import com.mt.model.MixedValues;
import com.mt.mtbletools.R;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.MTBLEDevice.MTBLEDEVICETYPE;
import com.mt.sdk.ble.MTBLEManager.MTScanCallback;
import com.mt.view.DeviceView;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class ScanFragment extends Fragment {

	public static final String SELECTDEVICE = "SELECTDEVICE";

	private MTBLEManager manger;
	private Handler handle = new Handler();
	private GlobalVariable mGlobalVariable;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mGlobalVariable = GlobalVariable.getinstance();
		this.manger = mGlobalVariable.getBleManger();
		
		if (!this.manger.isEnable()) {
			startActivityForResult(new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
		}
		
	}

	private View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (view != null) {
			return view;
		}
		view = inflater.inflate(R.layout.fragment_scan, container, false);

		initView();

		return view;
	}

	// 初始化控件
	private ListView device_listview;
	private SwipeRefreshLayout pulltoreflash_layout;
	private Button cfg_btn;

	private void initView() {
		cfg_btn = (Button) view.findViewById(R.id.cfg_btn);
		device_listview = (ListView) view.findViewById(R.id.device_listview);
		pulltoreflash_layout = (SwipeRefreshLayout) view.findViewById(R.id.pulltoreflash_layout);
		
		device_listview.setAdapter(listadapter);

		pulltoreflash_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

			@Override
			public void onRefresh() {
				manger.stopScan();
				mGlobalVariable.getDeviceList().clear();
				listadapter.notifyDataSetChanged();
				handle.postDelayed(new Runnable() {

					@Override
					public void run() {
						pulltoreflash_layout.setRefreshing(false);
						manger.startScan(scanCallback);
					}
				}, 1000);
			}
		});

		device_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if ((position > (mGlobalVariable.getDeviceList().size() - 1)) || (position < 0)) {
					return;
				}

				MTBLEDevice device = mGlobalVariable.getDeviceList().get(position);
				
				if(device.getSetlev() > 1){
					Toast.makeText(getContext(), "不允许连接", Toast.LENGTH_SHORT).show();
					return;
				}

				// 开发者用户
				if (mGlobalVariable.getMixedvalues().getUsermodel() == MixedValues.DEVELOPUSER) {
					Intent intent = new Intent(getActivity(), AdvertisementActivity.class);
					intent.putExtra(SELECTDEVICE, position);
					getActivity().startActivity(intent);
					return;
				}

				// 智能识别设备
				if ((device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon1)
						|| (device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon2)
						|| (device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon3)) {
					Intent intent = new Intent(getActivity(), MTBeacon123Activity.class);
					intent.putExtra(SELECTDEVICE, position);
					getActivity().startActivity(intent);
					return;
				}

				if (device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon4) {
					Intent intent = new Intent(getActivity(), MTBeacon4Activity.class);
					intent.putExtra(SELECTDEVICE, position);
					getActivity().startActivity(intent);
					return;
				}

				if (device.getDevicetype() == MTBLEDEVICETYPE.MTBLE) {
					Intent intent = new Intent(getActivity(), MTSeriTalkActivity.class);
					intent.putExtra(SELECTDEVICE, position);
					getActivity().startActivity(intent);
					return;
				}

				if (device.getDevicetype() == MTBLEDEVICETYPE.MTWX) {
					Intent intent = new Intent(getActivity(), MTWXCfgActivity.class);
					intent.putExtra(SELECTDEVICE, position);
					getActivity().startActivity(intent);
					return;
				}

				Intent intent = new Intent(getActivity(), AdvertisementActivity.class);
				intent.putExtra(SELECTDEVICE, position);
				getActivity().startActivity(intent);
				return;
			}
		});

		cfg_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(getContext(), AppCfgActivity.class));
			}
		});
	}

	// 列表适配器
	private BaseAdapter listadapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (null == convertView) {
				convertView = new DeviceView(getContext());
			}

			((DeviceView) convertView).setDatas(getItem(position));

			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public MTBLEDevice getItem(int position) {
			return mGlobalVariable.getDeviceList().get(position);
		}

		@Override
		public int getCount() {
			return mGlobalVariable.getDeviceList().size();
		}
	};

	// 扫描过滤器
	private boolean scanFilter(MTBLEDevice device) {

		if ((mGlobalVariable.getMixedvalues().getUsermodel() == MixedValues.SMARTUSER)
				|| (mGlobalVariable.getMixedvalues().getUsermodel() == MixedValues.DEVELOPUSER)) { // 智能识别用户，所有设备都可以扫描到
			return true;
		}

		if (mGlobalVariable.getMixedvalues().getUsermodel() == MixedValues.MTBEACONUSER) { // MTBeacon用户，所有设备都可以扫描到

			if ((device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon1)
					|| (device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon2)
					|| (device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon3)
					|| (device.getDevicetype() == MTBLEDEVICETYPE.MTBeacon4)) {
				return true;
			}
			return false;
		}

		if (mGlobalVariable.getMixedvalues().getUsermodel() == MixedValues.MTSERIUSER) { // MTSeri用户，所有设备都可以扫描到

			if (device.getDevicetype() == MTBLEDEVICETYPE.MTBLE) {
				return true;
			}
			return false;
		}

		if (mGlobalVariable.getMixedvalues().getUsermodel() == MixedValues.MTWXUSER) { // MTSeri用户，所有设备都可以扫描到

			if (device.getDevicetype() == MTBLEDEVICETYPE.MTWX) {
				return true;
			}
			return false;
		}

		return true;
	}

	@Override
	public void onResume() {
		super.onResume();
		System.out.println("onResume");
		manger.startScan(scanCallback);
	}

	@Override
	public void onPause() {
		super.onPause();
		manger.stopScan();
	}

	private MTScanCallback scanCallback = new MTScanCallback() {

		@Override
		public void onScanFail(int errocode, String erromsg) {

		}

		@Override
		public void onScan(MTBLEDevice device) {

			if (!scanFilter(device)) { // 不符合规则的，就不要继续进行
				return;
			}

			for (MTBLEDevice MTBLEDevice : mGlobalVariable.getDeviceList()) {
				if (MTBLEDevice.getDevice().getAddress().equals(device.getDevice().getAddress())) {
					MTBLEDevice.reflashInf(device);
					listadapter.notifyDataSetChanged();
					return;
				}
			}
			mGlobalVariable.getDeviceList().add(device);
			listadapter.notifyDataSetChanged();
		}
	};
}
